<template>
    <el-form :model="forms" ref="formRef" label-width="120px" style="padding: 20px;">
        <!-- 表单头部 -->
        <el-row :gutter="20">
            <el-col :span="8">
                <el-form-item label="报损单号：">
                    <el-input v-model="forms[0].lossreportnumber" placeholder="可不填写，自动生成"></el-input>
                </el-form-item>
                <el-form-item label="制单人" prop="makeasingle" required>
                    <el-input v-model="forms[0].makeasingle" disabled></el-input>
                </el-form-item>
                <el-form-item label="备注" prop="remark">
                    <el-input type="textarea" v-model="forms[0].remark"></el-input>
                </el-form-item>
            </el-col>
            <el-col :span="8">
                <el-form-item label="报损类型" required>
                    <el-select v-model.number="forms[0].thetypeoflossreport" placeholder="请选择">
                        <el-option label="损坏报损" value="损坏报损"></el-option>
                        <el-option label="丢失报损" value="丢失报损"></el-option>
                        <el-option label="其他报损" value="其他报损"></el-option>
                    </el-select>
                </el-form-item>

                <el-form-item label="制单时间">
                    <el-input v-model="forms[0].thetimewhentheorderwasmade" disabled></el-input>
                </el-form-item>
            </el-col>
            <el-col :span="8">
                <el-form-item label="关联订单号" required>
                    <el-input v-model="forms[0].associatetheordernumber"></el-input>
                </el-form-item>
            </el-col>
        </el-row>
        <div>
            <el-button type="primary" size="small" icon="el-icon-plus" @click="centerDialogVisible = true"
                style="float: right; margin-bottom: 10px;">新增产品</el-button>
        </div>
        <!-- 产品表格 -->
        <el-table :data="products" style="margin-top: 20px;" border>
            <el-table-column type="selection" width="55" />
            <el-table-column type="index" width="50"></el-table-column>
            <el-table-column label="产品名称" prop="proName"></el-table-column>
            <el-table-column label="产品编码" prop="proId"></el-table-column>
            <el-table-column label="规格" prop="specifications"></el-table-column>
            <el-table-column label="批次" prop="batch">
                <template #default="{ row }">
                    <span>{{ row.batch }}</span>
                </template>
            </el-table-column>
            <el-table-column label="单价" prop="unitprice"></el-table-column>
            <el-table-column label="报损数量">
                <template #default="{ row }">
                    <el-input v-model.number="row.reportedlossquantity" size="small" type="number"
                        @input="calculateTotal(row)"></el-input>
                </template>
            </el-table-column>
            <el-table-column label="报损库位" prop="thecurrentlocation">
                <template #default="{ row }">
                    <el-input v-model.number="row.thecurrentlocation" size="small" type="number"
                        @input="calculateTotal(row)"></el-input>
                </template>
            </el-table-column>
            <el-table-column label="原库位" prop="binlocation">
                <template #default="{ row }">
                    <span>{{ row.binlocation }}</span>
                </template>
            </el-table-column>
            <el-table-column label="操作" width="80">
                <template #default="{ row }">
                    <el-button size="small" icon="el-icon-edit" @click="deleteProduct(row)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>

        <!-- 操作按钮 -->
        <div style="margin-top: 20px;">
            <el-button type="primary" @click="submitForm">提交</el-button>
            <el-button @click="cancelForm" style="margin-left: 10px;">取消</el-button>
        </div>
    </el-form>

    <el-dialog v-model="centerDialogVisible" title="选择产品" style="width: 1300px;height: 900px;" center>
        <span>
            <div class="search-container">
                <el-input v-model="from.ProductId" placeholder="请输入产品编号" clearable :disabled="loading" />
                <el-input v-model="from.ProductName" placeholder="请输入产品名称" clearable :disabled="loading" />
                <el-button type="primary" @click="handleSearch">搜索</el-button>
            </div>
            <el-table :data="productsData" style="width: 100%;" border row-key="id" ref="productTableRef">
                <el-table-column type="selection" />
                <el-table-column type="index" label="序号"></el-table-column>
                <el-table-column prop="proId" label="产品编码"></el-table-column>
                <el-table-column prop="proName" label="产品名称"></el-table-column>
                <el-table-column prop="specifications" label="规格"></el-table-column>
                <el-table-column prop="无" label="类别"></el-table-column>
                <el-table-column prop="specifications" label="存储单位"></el-table-column>
                <el-table-column prop="无" label="包装类型"></el-table-column>
                <el-table-column prop="unitprice" label="单价"></el-table-column>
                <el-table-column prop="无" label="重量"></el-table-column>
            </el-table>
            <!-- 新增分页组件 -->
            <el-pagination v-show="from.totalPage > 1" :current-page="from.PageIdex" :page-sizes="[4, 8, 12]"
                :total="from.totalCount" @size-change="handlePageSizeChange" @current-change="handleCurrentChange" />
        </span>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="addSelectedProducts">添加</el-button>
                <el-button type="primary" @click="centerDialogVisible = false">
                    关闭
                </el-button>
            </div>
        </template>
    </el-dialog>
</template>

<script setup>
import axios from 'axios';
import { ref, reactive, onMounted } from 'vue';
import { ElTable } from 'element-plus';
import { saveAs } from 'file-saver';
import { ElMessage, ElMessageBox } from 'element-plus'
import { useRouter, useRoute } from 'vue-router';
import { useCounterStore } from "@/stores/counter";
import { KongaUrl } from '@/axios/axiosHelp'
const router = useRouter();
const route = useRoute();
const Store = useCounterStore()

var inboundNum = route.query.inboundNum;
// 表单数据数组
const forms = reactive([{
    "lossreportnumber": Math.floor(Math.random() * (999 - 100 + 1)) + 100,
    "thetypeoflossreport": "",
    "associatetheordernumber": "",
    "makeasingle": Store.user?.userName || '未知用户',
    "thetimewhentheorderwasmade": new Date().toISOString(),
    "remark": "",
    "productname": "",
    "productcode": "",
    "specification": "",
    "batch": "",
    "unitprice": "",
    "reportedlossquantity": "",
    "warehouse": "",
    "thecurrentlocation": "",
    "reviewstatus": 101,
    "reviewers": "无",
    "reasonforreview": "无",
    "reviewtime": new Date().toISOString(),
    "isDelete": 0
}]);
// 计算总价
const calculateTotal = (row) => {
    row.price = parseFloat(row.unitprice) || 0;
    row.quantity = parseFloat(row.reportedlossquantity) || 0;
    row.totalPrice = row.price * row.quantity;
};
// 提交表单
const submitForm = () => {
    // 构建字段数组结构
    const submitData = {
        Lossreportnumber: products.value.map(() => String(forms[0].lossreportnumber)),
        Thetypeoflossreport: products.value.map(() => forms[0].thetypeoflossreport),
        Associatetheordernumber: products.value.map(() => forms[0].associatetheordernumber),
        Makeasingle: products.value.map(() => forms[0].makeasingle),
        Thetimewhentheorderwasmade: products.value.map(() => forms[0].thetimewhentheorderwasmade),
        Remark: products.value.map(() => forms[0].remark),
        Productname: products.value.map(p => p.proName),
        Productcode: products.value.map(p => p.proId),
        Specification: products.value.map(p => p.specifications),
        Batch: products.value.map(p => p.batch),
        Unitprice: products.value.map(p => String(p.unitprice)),
        Reportedlossquantity: products.value.map(p => String(p.reportedlossquantity)),
        Warehouse: products.value.map(p => p.binlocation),
        Thecurrentlocation: products.value.map(p => String(p.thecurrentlocation)),
        Reviewstatus: products.value.map(() => forms[0].reviewstatus),
        Reviewers: products.value.map(() => forms[0].reviewers),
        Reasonforreview: products.value.map(() => forms[0].reasonforreview),
        Reviewtime: products.value.map(() => forms[0].reviewtime),
        IsDelete: products.value.map(() => forms[0].isDelete)
    };

    console.log('提交的数据:', submitData);
    // 提交请求
    KongaUrl.post('wangjunlong1/api/Reportlosses/ReportlossesAdd', submitData).then((res) => {
        if (res.data.code === 212) {
            ElMessage.success('提交成功');
            router.push('/Reportlosses');
        } else {
            ElMessage.error('提交失败');
        }
    }).catch((error) => {
        if (error.response) {
            ElMessage.error(`提交请求失败，状态码: ${error.response.status}，错误信息: ${error.response.data}`);
        } else if (error.request) {
            ElMessage.error('提交请求已发送，但没有收到响应');
        } else {
            ElMessage.error('提交请求时发生错误: ' + error.message);
        }
        console.error('接口错误：', error);
    });
};

const centerDialogVisible = ref(false);
const from = reactive({
    ProductId: '',
    ProductName: '',
    PageIdex: 1,
    PageSize: 15,
    totalPage: 0,
    totalCount: 0
});

const productsData = ref([]);
const loading = ref(false);
const productTableRef = ref(null);

const Moks = () => {
    loading.value = true;
    KongaUrl("wangjunlong/api/Store/Storeproduct", {
        params: {
            ProductId: from.ProductId,
            ProductName: from.ProductName,
            PageIdex: from.PageIdex,
            PageSize: from.PageSize,
        }
    }).then((res) => {
        console.log(res.data.data.list)
        productsData.value = res.data.data.list;
        from.totalCount = res.data.data.totalCount;
        from.totalPage = res.data.data.totalPage;
    }).finally(() => {
        loading.value = false;
    });
};

const handlePageSizeChange = (size) => {
    from.PageSize = size;
    from.PageIdex = 1;
    Moks();
};

const handleCurrentChange = (page) => {
    from.PageIdex = page;
    Moks();
};

const handleSearch = () => {
    from.PageIdex = 1;
    Moks();
};

const addSelectedProducts = () => {
    if (!productTableRef.value) {
        ElMessage.error("请先搜索产品");
        return;
    }
    const selectedRows = productTableRef.value.getSelectionRows();
    if (selectedRows.length === 0) {
        ElMessage.warning("请至少选择一个产品");
        return;
    }
    const newProducts = selectedRows.map(product => ({
        ...product,
        price: product.unitprice || 0,
        reportedlossquantity: 0,
        totalPrice: 0,
        batch: product.batch || '',
        thecurrentlocation: product.thecurrentlocation || '',
        warehouse: product.warehouse || '' // 确保原库位有值
    }));
    products.value = [...products.value, ...newProducts];
    centerDialogVisible.value = false;
};

const products = ref([]);
// 取消表单操作
const cancelForm = () => {
    // 重置表单数据
    Object.keys(forms[0]).forEach(key => forms[0][key] = '');
    // 清空表格数据
    products.value = [];
};

// 自动生成入库单号
onMounted(() => {
    Moks();
    if (!forms[0].lossreportnumber) {
        generateInboundNumber();
    }
});

const generateInboundNumber = async () => {
    try {
        const response = await axios.get('/api/inbound-orders/generate-number');
        forms[0].lossreportnumber = response.data;
    } catch (error) {
        ElMessage.error('生成报损单号失败');
    }
};
const deleteProduct = (row) => {
    products.value = products.value.filter(item => item.id !== row.id);
    ElMessage.success('产品删除成功');
};
</script>

<style scoped>
.el-table {
    width: 100%;
}

.search-container {
    display: flex;
    align-items: center;
    gap: 10px;
    margin-bottom: 15px;
}

.search-container .el-input {
    flex: 1;
    max-width: 200px;
}
</style>